
package com.kweative.network;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import org.codehaus.jackson.util.ByteArrayBuilder;

/**
 *
 * @author henrik
 */
abstract public class Response {
    private Request request;
    private Status status = Status.OK;
    private HashMap<String,String> headers = new HashMap<String, String>();
    private byte[] body;

    public void clear() {
        body = null;
        status = Status.OK;
        headers.clear();;
        request = null;
    }

    public Request getRequest() {
        return request;
    }

    public void setRequest(Request request) {
        this.request = request;
    }

    
    public byte[] getBody() {
        return body;
    }
    
    public void setBody(String body) {
        try {
            this.body = body.getBytes("UTF-8");
        } catch (UnsupportedEncodingException ex) {
            this.body = body.getBytes();
        }
    }
    public void setBody(byte[] body) {
        this.body = body;
    }
    public void addBody(byte[] body) {
        ByteArrayBuilder bb = new ByteArrayBuilder();
        if (this.body != null)
            bb.write(this.body);
        bb.write(body);
        this.body = bb.toByteArray();
        bb.close();
    }
    public void addBody(String body) {
        try {
            addBody(body.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            addBody(body.getBytes());
        }
    }

    public HashMap<String, String> headers() {
        return headers;
    }

    public Status getStatus() {
        return status;
    }

    public void setStatus(Status status) {
        this.status = status;
    }
    
    abstract public void write(OutputStream out) throws IOException;



    public enum Status {
        OK,
        MOVED,
        E_INTERNAL,
        E_REQUEST,
        E_FORMAT,
        E_NOTFOUND
    }
}
